const { program } = require('commander');
const path = require('path');
const TemplateReader = require('./lib/templateReader');
const ChatGLMGenerator = require('./lib/aiGenerator');
const CodeGenerator = require('./lib/codeGenerator');
const ProjectBuilder = require('./lib/projectBuilder');

async function main(options) {
  try {
    // 修改模板路径，使用正确的相对路径
    const templatePath = path.join(__dirname, './codeTemplate/src/pages');
    const templateReader = new TemplateReader(templatePath);
    const codeGenerator = new CodeGenerator(ChatGLMGenerator);
    const projectBuilder = new ProjectBuilder(options.output);

    // 读取所有模板
    const templates = await templateReader.getTemplates();
    
    // 添加调试日志
    console.log('Found templates:', Object.keys(templates));
    
    // 生成代码
    const generatedCode = {};
    for (const [pageName, template] of Object.entries(templates)) {
      console.log(`Generating code for ${pageName}...`);
      const aiResponse = await ChatGLMGenerator.generateCode(
        options.prompt,
        template.prompt
      );
      generatedCode[pageName] = codeGenerator.processAIResponse(aiResponse);
    }

    // 构建项目
    await projectBuilder.buildProject(templates, generatedCode);
    
    console.log('项目生成完成！');
  } catch (error) {
    console.error('生成失败:', error);
    console.error('错误详情:', error.stack);
    process.exit(1);
  }
}

// 命令行配置
program
  .version('1.0.0')
  .option('-p, --prompt <string>', '用户需求描述')
  .option('-o, --output <path>', '输出目录', './output')
  .parse(process.argv);

const options = program.opts();

if (!options.prompt) {
  console.error('请提供需求描述');
  process.exit(1);
}

main(options); 